<template>
  <base-layout
    :dialog-title="dialogTitle"
    :dialog-visible="dialogVisible"
    @dialog-close="dialogClose"
    :dialogWidth="dialogWidth"
    :visibleContent="true"
    :visibleContent2="true"
    :visibleContent3="true"
  >
    <template #contentPanel>
      <el-row>
        <el-col :span="22">套餐信息</el-col>
      </el-row>
      <el-row>
        <el-form
          :model="addForm"
          label-width="130px"
          :show-message="false"
          :rules="addFormRules"
          ref="addForm"
        >
          <el-row>
            <el-col :span="4">
              <div style="margin: 20px; text-align: center">
                <el-upload
                  action=""
                  :show-file-list="false"
                  list-type="picture-card"
                  :http-request="httpRequest"
                >
                  <img v-if="photosUrl" :src="photosUrl" alt="" class="avatar" />
                  <i class="el-icon-plus" v-else></i>

                  <div class="el-upload__tip" slot="tip">套餐图片</div>
                </el-upload>
              </div>
            </el-col>
            <el-col :span="20">
              <el-row>
                <el-col :span="8">
                  <el-form-item label="套餐名称:" prop="carPackageName">
                    <el-input
                      v-model="addForm.carPackageName"
                      clearable
                      maxlength="20"
                      placeholder="请输入套餐名称"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="套餐所属类别:" prop="carPackageDistId">
                    <el-select
                      clearable
                      placeholder="请选择"
                      v-model="addForm.carPackageDistId"
                    >
                      <el-option
                        v-for="item in dict['套餐所属类别']"
                        :key="item.index"
                        :value="item.value"
                        :label="item.text"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="状态:" prop="status">
                    <el-switch
                      v-model="addForm.status"
                      :active-text="addForm.status ? '启用' : '关闭'"
                      active-color="#13ce66"
                    >
                    </el-switch>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="套餐总工时:" prop="carPackageSumHours">
                    <el-input
                      v-model="addForm.carPackageSumHours"
                      clearable
                      disabled
                      maxlength="20"
                      placeholder="请输入套餐总工时"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="套餐总金额:" prop="carPackageAmount">
                    <el-input
                      v-model="addForm.carPackageAmount"
                      clearable
                      disabled
                      maxlength="20"
                      placeholder="请输入套餐总金额"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="所属门店:" prop="storeId">
                    <job-shop v-model="addForm.storeId" placeholder="所属门店" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="16">
                  <el-form-item label="备注:" prop="remark">
                    <el-input
                      type="textarea"
                      v-model="addForm.remark"
                      clearable
                      placeholder="请输入备注"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-form>
      </el-row>
    </template>

    <template #contentPanel2>
      <el-row>
        <el-col :span="6">套餐所包含项目</el-col>
        <el-col :span="18" align="right">
          <el-button type="primary" @click="handleDataInsert('项目选择')"
            >添加项目</el-button
          >
        </el-col>
      </el-row>
      <el-row>
        <data-table
          :value="tableProjectList"
          :total-count="tableProjectList.length"
          :has-action="true"
          :table-column-attributes="tableColumnProjectAttributes"
          :isShowPage="true"
          :width="85"
          :localPage="true"
        >
          <template #action="{ row }">
            <i
              class="el-icon-delete"
              title="删除"
              style="color: red; cursor: pointer"

              @click="tablistDelete(row, 1)"
            ></i>
          </template>
        </data-table>
      </el-row>
    </template>

    <template #contentPanel3>
      <el-row>
        <el-col :span="6">套餐所包含配件</el-col>
        <el-col :span="18" align="right">
          <el-button type="primary" @click="handleDataInsert('配件选择')"
            >添加配件</el-button
          >
        </el-col>
      </el-row>
      <el-row>
        <data-table
          :value="tableFittingList"
          :total-count="tableFittingList.length"
          :has-action="true"
          :table-column-attributes="tableColumnFittingAttributes"
          :isShowPage="true"
          :width="80"
          :localPage="true"
        >
          <template #action="{ row }">
            <i
              class="el-icon-delete"
              title="删除"
              style="color: red; cursor: pointer"

              @click="tablistDelete(row, 2)"
            ></i>
          </template>
        </data-table>
      </el-row>
      <el-row>
        <el-col :span="24" align="right">
          <el-button type="primary" style="width: 100px" @click="saveUpdate"
            >保存</el-button
          >
        </el-col>
      </el-row>
    </template>

    <template #dialog>
      <SelectProject v-if="dialogTitle == '项目选择'" @getList="changeListCheck" />
      <SelectAccessories v-if="dialogTitle == '配件选择'" @partsList="changeListCheck" />
    </template>
  </base-layout>
</template>

<script>
import baseMixin from "@/mixins/base";
import { parseTimeToYMDHMS, fileUpload, getDict, getImageUrl } from "@/utils";
import { JobShop } from "@/components/index";
import { SelectProject } from "@/components/index";
import SelectAccessories from "@/components/SelectAccessories";
import {
  addCarPackage,
  editCarPackage,
  getCarPackageFindById,
} from "@/api/after-sale/client/package";
export default {
  components: { SelectProject, SelectAccessories, JobShop },
  props: {
    value: {
      type: Object,
      default: () => ({}),
    },
    menus: {
      type: Object,
    },
  },
  mixins: [baseMixin({})],
  data() {
    return {
      photosUrl: "", //显示图片
      addForm: {
        carPackageName: "", //套餐名称
        carPackageDistId: "", //套餐所属类别
        carPackageSumHours: "", //套餐总工时
        carPackageAmount: "", //套餐总金额
        carPackageImage: "", //套餐图片
        storeId: "",
        carProjectList: [], //套餐中的项目
        carPartsList: [], //套餐中的配件
        remark: "", //remark
        status: true, //状态
        id: "",
      },
      tableProjectList: [],
      tableFittingList: [],
      tableColumnProjectAttributes: [
        { name: "项目名", value: "projectName", type: "text" },
        { name: "项目介绍", value: "remark", type: "text" },
        {
          name: "项目工时",
          value: "workHours",
          type: "text",
        },
        { name: "项目类型", value: "projectDictValue", type: "text" },
        {
          name: "项目工时费",
          value: "amount",
          type: "render",
          render: (row, value) => {
            return `￥${value}`;
          },
        },
        { name: "项目提成点", value: "commission", type: "text" },
      ],
      tableColumnFittingAttributes: [
        { name: "配件编号", value: 'partsCode', type: 'text' },
        { name: '配件名称', value: 'partsName', type: 'text' },
        { name: '配件类别', value: 'partsDictValue', type: 'text' },
        { name: '配件单位', value: 'unit', type: 'text' },
        { name: '数量', value: 'internalNum', type: 'inputNumber', maxFiled: 1000000 },
      ],
      dialogVisible: false,
      dialogWidth: '1100px',
      dict: {},
      addFormRules: {},
    };
  },
  async created() {
    this.dict = getDict(['套餐所属类别']);
    if (this.$route.query.id) {
      let { data } = await getCarPackageFindById(this.$route.query.id);
      this.addForm = data;
      this.photosUrl = getImageUrl(data.carPackageImage);
      this.tableProjectList = data.carProjectList?data.carProjectList:[];
      this.tableFittingList = data.carPartsList?data.carPartsList:[];
    }
  },
  methods: {
    //表格删除事件
    tablistDelete(row, type) {
      let name = type == 1 ? 'tableProjectList' : 'tableFittingList';
      this[`${name}`].forEach((item, index) => {
        if (item.id == row.id) {
          this[`${name}`].splice(index, 1)
        }
      });
    },
    //项目或配件选择
    changeListCheck(list) {
      this.filterList(list)
    },
    filterList(list) {
      let fildName = `${
        this.dialogTitle == '项目选择' ? 'tableProjectList' : 'tableFittingList'
      }`
      //项目过滤
      if (this[fildName].length > 0) {
        this[fildName].forEach((item) => {
          list.forEach((item2, index) => {
            if (item2.id == item.id) {
              list.splice(index, 1)
            }
          })
        })
        this[fildName] = Object.assign([], this[fildName].concat(list));
      } else {
        this[fildName] = list
      }
      this.dialogClose()
      this.countTotalAmount()
    },
    // 计算总工时和总金额
    countTotalAmount() {
      let totalHouer = 0,
        totalAmout = 0
      this.tableProjectList.forEach((item) => {
        if (item.workHours) {
          totalHouer += Number(item.workHours)
        }
        if (item.amount) {
          totalAmout += Number(item.workHours) * item.amount
        }
      })
      this.addForm.carPackageSumHours = totalHouer
      this.addForm.carPackageAmount = totalAmout
    },
    async saveUpdate() {
      this.$refs.addForm.validate(async(valid) => {
        if (valid) {
          /** 保存*/
          let option = this.addForm
          option.carProjectList = []
          this.tableProjectList.forEach((item) => {
            option.carProjectList.push({
              carProjectId: item.id,
              id: this.addForm.id
            })
          })
          option.carPartsList = []
          this.tableFittingList.forEach((item) => {
            option.carPartsList.push({
              ...item,
              carPartsId: item.id,
              id: this.addForm.id
            })
          })
          const { success } = this.addForm.id
            ? await editCarPackage(this.addForm)
            : await addCarPackage(this.addForm)
          if (success) {
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.closeRouter('/client-manage/package')
          } else {
            this.$message.error('操作失败')
          }
        }
      })
    },
    //文件上传
    httpRequest(value) {
      fileUpload(value.file).then((res) => {
        let { success, data } = res;
        if (success) {
          this.addForm.carPackageImage = data.id;
          this.photosUrl = getImageUrl(data.id);
        }
      });
    },
  },
  mounted() {},
};
</script>

<style lang="scss" scoped>
.el-table .delete-row {
  background: #f5f7fa;
  color: #ccc !important;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 150px;
  height: 150px;
  display: block;
}
</style>
